package com.aaron.kjviewutils.driving;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.aaron.kjviewutils.BaseActivity;
import com.aaron.kjviewutils.R;
import com.aaron.kjviewutils.footballleague.TabPagerStateAdapter;
import com.aaron.kjviewutils.retrofit.RetrofitUtil;
import com.github.ybq.android.spinkit.Style;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Aaron on 2017/3/3.
 */

public class DrivingTopicActivity extends BaseActivity {

    @Bind(R.id.drivingTopicToolBar)
    Toolbar drivingTopicToolBar;
    @Bind(R.id.barTitle)
    TextView barTitle;
    @Bind(R.id.leftBarIcon)
    ImageView leftBarIcon;
    @Bind(R.id.drivingTopicTabs)
    TabLayout drivingTopicTabs;
    @Bind(R.id.drivingTopicViewpager)
    ViewPager drivingTopicViewpager;

    private TabPagerStateAdapter adapter;
    private List<Fragment> fragments;
    private Call<ResponseBody> zhuantiCall;
    private DrivingTopicService drivingTopicService;
    private List<String> tabs;

    @OnClick(R.id.leftBarIcon)
    void leftBarIconClick()
    {
        closeSelf(DrivingTopicActivity.this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.layout_driving_topic);
        ButterKnife.bind(this);
        initTitle();
        initContent();
    }

    private void initTitle()
    {
        drivingTopicToolBar.setTitle("");
        barTitle.setText("专项题库分类");
        loadBackground(leftBarIcon, resources.getDrawable(R.mipmap.back));
        drivingTopicToolBar.setNavigationIcon(null);
    }

    Runnable runnableLoadData = new Runnable() {
        @Override
        public void run() {
            if(null!=progress)
            {
                progress.showProgress(Style.WAVE);
                progress.showAtLocation(drivingTopicToolBar, Gravity.CENTER, 0, 0);
            }
            if(null!=drivingTopicService)
            {
                zhuantiCall = drivingTopicService.obtainZhuantiCategroy();
                zhuantiCall.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        zhuantiCall.cancel();
                        if(null!=progress)
                        {
                            progress.dismissView();
                        }
                        try {
                            String source = response.body().string();
                            if(!TextUtils.isEmpty(source))
                            {
                                JSONObject json01 = new JSONObject(source);
                                if("200".equals(json01.getString("retCode")))
                                {
                                    tabs = new ArrayList<String>();
                                    fragments = new ArrayList<Fragment>();
                                    JsonParser jsonParser = new JsonParser();
                                    JsonObject json02 = jsonParser.parse(source).getAsJsonObject();
                                    JsonObject json03 = json02.getAsJsonObject("result");
                                    Iterator<Map.Entry<String, JsonElement>> iterator = json03.entrySet().iterator();
                                    while (iterator.hasNext())
                                    {
                                        Map.Entry<String, JsonElement> elementEntry = iterator.next();
                                        tabs.add(elementEntry.getKey());
                                        DrivingTopicFragment drivingTopicFragment = new DrivingTopicFragment();
                                        Bundle bundle = new Bundle();
                                        bundle.putString("data", elementEntry.getValue().toString());
                                        drivingTopicFragment.setArguments(bundle);
                                        fragments.add(drivingTopicFragment);
                                    }
                                    adapter = new TabPagerStateAdapter(getSupportFragmentManager(), fragments);
                                    drivingTopicViewpager.setAdapter(adapter);
                                    drivingTopicTabs.setupWithViewPager(drivingTopicViewpager);
                                    drivingTopicTabs.setTabMode(TabLayout.MODE_SCROLLABLE);
                                    int size = tabs.size();
                                    for(int i=0; i<size; i++)
                                    {
                                        //初始化tabs
                                        TabLayout.Tab tab = drivingTopicTabs.getTabAt(i);
                                        tab.setCustomView(getTabsItem(tabs.get(i)));
                                    }
                                }
                                else
                                {
                                    showMsg(json01.getString("msg"));
                                }
                            }
                            else
                            {
                                showMsg("获取数据失败");
                            }

                        } catch (Exception e) {
                            showMsg("获取数据失败");
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        zhuantiCall.cancel();
                        if(null!=progress)
                        {
                            progress.dismissView();
                        }
                        showMsg("获取数据失败");
                    }
                });
            }
        }
    };

    private void initContent()
    {
        if(null==retrofit)
        {
            retrofit = RetrofitUtil.obtainRetrofit();
        }
        drivingTopicService = retrofit.create(DrivingTopicService.class);
        mHandler.postDelayed(runnableLoadData, 1000);
    }

    private View getTabsItem(String tag)
    {
        View view = inflater.inflate(R.layout.tas_item, null, false);
        TextView tabsTag = (TextView) view.findViewById(R.id.tabsTag);
        tabsTag.setText(tag);
        return view;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN)
        {
            //关闭
            closeSelf(DrivingTopicActivity.this);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null!=mHandler)
        {
            mHandler.removeCallbacks(runnableLoadData);
        }
        if(null!=zhuantiCall)
        {
            zhuantiCall.cancel();
        }
        ButterKnife.unbind(this);
    }
}
